<<template>
	<el-dialog :title="title" :visible.sync="show" width="85%" :close-on-click-modal='false'>
    <div style="position: relative"> 
        <div style="margin-bottom: 20px;">
          <label>短语名称：</label>
            <el-input
              placeholder="请输入短语名称"
              v-model="name"
              style="width: 210px; margin-left: 15px;">
            </el-input>
        </div>
        <quill-editor ref="editor" v-model="content"
          :options="editorOption"
          @change="onEditorChange($event)">
        </quill-editor>
        <div :style="styleObject" class="sug_list">
          <ul>
            <li v-if="atom">
              <el-input v-model="keyword"></el-input>
              <el-button type="text" @click="searchAtom">搜索</el-button>
            </li>
            <li v-if="sugList.length == 0" @click="closeSugList">
              未查询到子项
            </li>
            <li v-for="item in sugList" :key="item.id" @click="selectItem(item,$event)">
              <span v-if="!item.variable">{{item.label}}</span>
              <el-input
                v-else
                v-model="item.label">
              </el-input>  
              
            </li>
          </ul>
        </div>
    </div>
    <div style="margin-top: 20px;" v-if ="showPreview" v-html="previewPhrase"></div>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="show = false">取 消</el-button>
      <el-button @click="preview">{{previewText}}</el-button>
      <el-button @click="save">确定</el-button>
	  </div>
	</el-dialog>
</template>
<script>
import api from "../../../api/api";
import Quill from 'quill';
import {
  AtomBlot,
  AtomParamBlot,
  OperatorBlot
} from "../../../common/quillBlock";
import quillEditor from "../../common/editor.vue";
import { clean } from '../../../util/clean.js';
export default {
  props: {
    id: null
    
  },
  created() {
    this.getDetail();
  },
  components: {
    quillEditor
  },
  computed: {
    title() {
      return this.id ? "编辑短语" : "新建短语";
    }
  },
  data() {
    return {
      show: true,
      sugList: [],
      showAtom: false,
      atomId: null,
      name: "",
      previewText: "预览",
      showPreview: false,
      previewPhrase: "",
      styleObject: {
        position: "absolute",
        left: "0px",
        top: "0px",
        display: "none"
      },
      rangeIndex: 1,
      atom: false,
      keyword: '',
      content: "",
      editorOption: {
        // some quill options
      }
    };
  },
  methods: {
    getDetail() {
      if (this.id) {
        api
          .getDataByID({
            tableName: "phrase",
            id: this.id
          })
          .then(res => {
            if (res.ret == 0) {
              
              this.name = res.data.name; 
              this.content = clean(res.data.template);
            } else {
              this.$message({
                type: "error",
                message: "查询短语信息失败！"
              });
            }
          })
          .catch(e => {
            this.$message({
              type: "error",
              message: "查询短语信息失败！"
            });
          });
      }
    },
    onEditorChange({ editor, html, text }) {
      let range = this.$refs.editor.quillEditor.getSelection();
      if (range) {
        let inputText = this.$refs.editor.quillEditor.getText(
          range.index - 1,
          2
        );
        this.rangeIndex = range.index;
        //console.log(this.$refs.editor.quillEditor.getContents(this.rangeIndex - 2));
        // debugger;
        if (
          inputText.indexOf("@") == -1 &&
          inputText.indexOf(".") == -1 &&
          inputText.indexOf("|") == -1
        ) {
          this.closeSugList();
        }
        if (inputText.indexOf("@") > -1) {
          this.getSugAtomList();
        }
        if (inputText.indexOf(".") > -1) {
          let delta = this.$refs.editor.quillEditor.getContents(
            this.rangeIndex - 1,
            1
          );
          this.listenDelta(delta, 1);
        }
        if (inputText.indexOf("|") > -1) {
          let delta = this.$refs.editor.quillEditor.getContents(
            this.rangeIndex - 1,
            1
          );
          this.listenDelta(delta, 2);
        }
      }

      this.content = html;
    },
    listenDelta(delta, type) {
      if (delta.ops.length > 0) {
        if (
          delta.ops[0].attributes &&
          delta.ops[0].attributes._id &&
          !delta.ops[0].attributes._atomid
        ) {
          this.atomId = delta.ops[0].attributes && delta.ops[0].attributes._id;
          if (type == 1) {
            this.getSugAtomParamList();
          }
        } else if (
          delta.ops[0].attributes &&
          delta.ops[0].attributes._id &&
          delta.ops[0].attributes._atomid
        ) {
          this.operatorItemId =
            delta.ops[0].attributes && delta.ops[0].attributes._uid;
          if (type == 2) {
            this.getOpreatorList();
          }
        } else if (
          typeof delta.ops[0].insert == "string" &&
          (delta.ops[0].insert[0] == "." || delta.ops[0].insert[0] == "|")
        ) {
          delta = this.$refs.editor.quillEditor.getContents(
            this.rangeIndex - 2,
            1
          );
          this.listenDelta(delta, type);
        }
      }
    },
    preview() {
      if (this.$refs.editor.quillEditor.getText().length > 1) {
        if (this.showPreview) {
          this.showPreview = false;
          this.previewText = "预览";
          return;
        }
        let form = {};
        form.template = this.content;
        api
          .getPreviewPhrase({
            form: form
          })
          .then(res => {
            this.previewPhrase = res.data;
            this.showPreview = true;
            this.previewText = "关闭预览";
          });
      }
    },
    save() {
      if (
        this.$refs.editor.quillEditor.getText().length > 0 &&
        this.name.length > 0
      ) {
        let form = {};
        if (this.id) {
          form.id = this.id;
        }
        form.name = this.name;
        form.template = clean(this.content);
        api
          .addOrEditSubmit({
            tableName: "phrase",
            form: form
          })
          .then(res => {
            if (res.ret == 0) {
              this.$message({
                type: "success",
                message: "添加或者更新短语成功！"
              });
              this.show = false;
              this.$emit("refresh");
            } else {
              this.$message({
                type: "error",
                message: "添加或者更新短语失败！"
              });
            }
          })
          .catch(e => {
            this.$message({
              type: "error",
              message: "添加或者更新短语失败！"
            });
          });
      }
      //console.log(this.content);
    },
    selectItem(atom, event) {
      if (event.target.tagName == 'INPUT') {
        event.stopPropagation();
        return;
      }
      let label = atom.label;
      let embed = "";
      var uid = Date.now();
      if (atom.a_type == 1) {
        this.atomId = atom.id;
        let randeIndex = this.rangeIndex || this.rangeIndex + 1;
        this.$refs.editor.quillEditor.insertEmbed(
          randeIndex,
          "Atom",
          { _id: atom.id, _uid: uid, _name: atom.name, _text: atom.label },
          Quill.sources.USER
        );
        this.closeSugList();
      }
      if (atom.a_type == 2) {
        let delta = this.$refs.editor.quillEditor.getContents(
          this.rangeIndex,
          1
        );
        if (delta.ops[0].insert == ".") {
          this.rangeIndex = this.rangeIndex + 1;
        }
        this.$refs.editor.quillEditor.insertEmbed(
          this.rangeIndex,
          "AtomParam",
          {
            _id: atom.id,
            _uid: uid,
            _atomId: atom.atom_id,
            _name: atom.name,
            _text: atom.label
          },
          Quill.sources.USER
        );
        this.closeSugList();
      }
      if (atom.a_type == 3) {
        let delta = this.$refs.editor.quillEditor.getContents(
          this.rangeIndex,
          1
        );
        if (delta.ops[0].insert == "|") {
          this.rangeIndex = this.rangeIndex + 1;
        }
        this.$refs.editor.quillEditor.insertEmbed(
          this.rangeIndex,
          "Operator",
          {
            _id: atom.id,
            _uid: uid,
            _tid: this.operatorItemId,
            _name: atom.label,
            _text: atom.label
          },
          Quill.sources.USER
        );
        this.closeSugList();
      }
    },
    getOpreatorList() {
      api.getOpreators().then(res => {
        this.sugList = res.data;
        let index = 1;
        this.sugList.forEach(element => {
          element.id = index++;
          element.a_type = 3;
        });
        this.atom = false;
        this.showSugList();
      });
    },
    getSugAtomParamList() {
      if (this.atomId) {
        api
          .getAtomParameters({
            tableName: "atom_parameter",
            atom_id: this.atomId
          })
          .then(res => {
            if (res.ret == 0) {
              this.sugList = res.data.dataList;
              this.sugList.forEach(element => {
                element.label = element.alias_name;
                element.a_type = 2;
              });
              this.atom = false;
              this.showSugList();
            }
          });
      }
    },
    getSugAtomList(keyword) {
      let filters = [
        {
          type: "1",
          key: "status",
          value: 1
        }
      ];

      let para = {
        currentPage: 0,
        pageNumb: 2000,
        wheres: JSON.stringify(filters),
        order: "id",
        tableName: "atom"
      };
      if (keyword) {
        para.like = JSON.stringify({
          key: 'name',
          value: keyword
        })
      }
      api
        .getList(para)
        .then(res => {
          if (res.ret == 0) {
            this.sugList = res.data.dataList;
            this.sugList.forEach(element => {
              element.label = element.name;
              element.a_type = 1;
            });
            this.atom = true;
            if (this.styleObject.display == "none") {
              this.showSugList();
            }
          }
        })
        .catch(e => {

          this.$message({
            type: "error",
            message: "获取原子列表失败"
          });
        });
    },
    searchAtom() {
      if (this.keyword) {
        this.getSugAtomList(this.keyword)
      } else {
        this.getSugAtomList();
      }
    },
    closeSugList() {
      this.showAtom = false;
      this.atom = false;
      this.styleObject.display = "none";
    },
    getLastChar(str) {
      let char = "";
      str = str.replace(/(^\s*)|(\s*$)/g, "");
      if (str && str.length > 0) {
        char = str.replace(/(^\s*)|(\s*$)/g, "").charAt(str.length - 1);
      }
      return char;
    },
    showSugList() {
      var toolBarHeight =
        document.querySelector(".ql-toolbar").offsetHeight + 56;
      var range = this.$refs.editor.quillEditor.getSelection();
      var bounds = this.$refs.editor.quillEditor.getBounds(range);
      var bottom = bounds ? bounds.bottom  + toolBarHeight : toolBarHeight;
      var left = bounds.left;
      this.styleObject.left = left + "px";
      this.styleObject.top = bottom + "px";
      this.styleObject.display = "block";
    }
  },
  watch: {
    show(val) {
      if (!val) {
        this.$emit("closedialog");
      }
    }
  }
};
</script>
<style>
.sug_list .el-input {
  width: 70%
}
</style>




